<template>
  <div class="login">
    <div class="login-title">生产质量管理系统</div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      label-width="auto"
      class="demo-ruleForm"
    >
      <!-- <div class="avatar">
        <el-avatar> user </el-avatar>
      </div> -->
      <el-form-item label="账号" prop="pass">
        <el-input v-model="ruleForm.pass" autocomplete="off" type="text" maxlength="6" />
      </el-form-item>
      <el-form-item label="密码" prop="checkPass">
        <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
          show-password="true"
          maxlength="6"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import "./index.scss";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { userinfo } from "@/request/axios";
import { ElMessage } from "element-plus";

const ruleFormRef = ref<FormInstance>();
const router = useRouter();
const ruleForm = reactive({
  pass: "",
  checkPass: "",
});

const submitForm = async (formEl: any) => {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (valid) {
    } else {
      console.log("error submit!");
      return false;
    }
  });
  const res: any = await userinfo({
    username: ruleForm.pass,
    password: ruleForm.checkPass,
  });
  console.log(res, "res");
  if (res?.data?.message == "success") {
    localStorage.setItem("loginId", res?.data?.id);
    localStorage.setItem(
      "users",
      JSON.stringify({
        username: ruleForm.pass,
        id: res?.data?.id,
        password: ruleForm.checkPass,
        avatar: `http://localhost:8000${res?.data?.avatar}`,
      })
    );
    router.push("/basicMatters");
  } else {
    ElMessage({
      message: res?.data?.message,
      type: "warning",
    });
  }
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
